
import yaml
import ruamel.yaml
from Common.Route import Any_Path
from Common.ReadYaml import ConfigYaml
from Common.FontColor import outcome


class RwYaml(object):

    def __init__(self, file_dir='Config', file_name="Config.yaml"):
        """
        :param file_name: 文件名称
        """
        self.yaml = yaml
        self.file = file_name
        self.file_path = Any_Path(file_dir, file_name)

    def read_yaml_data(self):
        """
        读取公共文件PubData数据
        :return:
        """

        with open(self.file_path, 'r', encoding='utf-8') as f:
            if float(yaml.__version__.split(".")[0]) > 4.0:
                data = yaml.load(f, Loader=yaml.FullLoader)
            else:
                data = yaml.load(f)
            return data

    def write_yaml(self, node, **kwargs):
        """
        写入新数据至公共文件，如果数据存在则不写入，如果不存在则写入
        :param node: 父节点
        :param key: 键
        :param value:  值
        :return:
        """

        old_data = self.read_yaml_data()
        if node in old_data:
            for key, value in kwargs.items():
                old_data[node][key] = value
        else:
            old_data.update({node: kwargs})

        with open(self.file_path, 'w', encoding='utf-8') as f:
            ruamel.yaml.round_trip_dump(old_data, f, default_flow_style=False, allow_unicode=True, indent=2, block_seq_indent=2)

    def read_yaml_value(self, note, key):
        """
        读取某一个键下的数据值
        :param note:  父节点
        :param key: 键
        :return:
        """
        with open(self.file_path, 'r', encoding='utf-8') as f:
            if float(yaml.__version__.split(".")[0]) > 4.0:
                data = yaml.load(f, Loader=yaml.FullLoader)
            else:
                data = yaml.load(f)
            try:
                if note in data.keys():
                    return data.get(note).get(key)
                else:
                    outcome('red', '节点nb:%s不存在！' % note)
            except KeyError as e:
                outcome('red', 'key：%s不存在！' % e)



